package com.whpost.service.service.t;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.whpost.service.dao.t.TCzyDao;
import com.whpost.service.dao.t.TFilesMapper;
import com.whpost.service.dao.t.TRoleDao;
import com.whpost.service.dao.t.TXzjgDao;
import com.whpost.service.entity.t.TCzy;
import com.whpost.service.entity.t.TFiles;
import com.whpost.service.entity.t.TRole;
import com.whpost.service.entity.t.TXzjg;
import com.whpost.service.entity.tools.ListInfo;
import com.whpost.service.entity.tools.PageInfo;
import com.whpost.service.entity.tools.ResultInfo;
import com.whpost.service.entity.tools.ServRtn;
import com.whpost.service.service.BaseServices;
import com.whpost.service.tools.ToolBean;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * Created by IntelliJ IDEA.
 *
 * @Author: Yin Zhuoyi
 * @Date: 2021/12/15 11:16
 */
@Service
public class TCzyServices extends BaseServices<TCzyDao, TCzy> {

    @Resource
    private TXzjgDao tXzjgDao;
    @Resource
    private TRoleDao tRoleDao;
    @Resource
    private TApiNonceService tApiNonceService;

    @Transactional
    public ResultInfo xgmm(String loginId, Map<String, Object> map) {
        JSONObject jsonObject = getData(map,loginId);
        if (StringUtils.isEmpty(loginId)){
            throw new RuntimeException("用户信息丢失!");
        }else{
            TCzy tCzy = getBaseMapper().getCzyById(loginId);
            String old_pwd = "",new_pwd = "",new_pwd1 = "";
            if (jsonObject.containsKey("old_pwd")) {
                old_pwd = jsonObject.getString("old_pwd");
            }
            if (jsonObject.containsKey("new_pwd")) {
                new_pwd = jsonObject.getString("new_pwd");
            }
            if (jsonObject.containsKey("new_pwd1")) {
                new_pwd1 = jsonObject.getString("new_pwd1");
            }
            old_pwd = ToolBean.getMD5Str(old_pwd);

            if (!old_pwd.equals(tCzy.getPwd()))
            {
                return new ResultInfo(500,"原密码错误！",null);
            }
            if(StringUtils.isEmpty(new_pwd))
            {
                return new ResultInfo(500,"新密码不能为空！",null);
            }
            if(!new_pwd.equals(new_pwd1))
            {
                return new ResultInfo(500,"新密码两次输入不一致！",null);
            }
            if (!ToolBean.checkPassWordIsStrong(new_pwd))
            {
                return new ResultInfo(500,"密码限制8-20位，要求大小写字母、数字、特殊符号至少包含两种!",null);
            }
            new_pwd = ToolBean.getMD5Str(new_pwd);
            int a = getBaseMapper().updateUserPwd(new_pwd,loginId);
            if (a>0)
            {
                return new ResultInfo(0,"修改成功！",null);
            }else{
                return new ResultInfo(500,"用户信息不存在！",null);
            }
        }
    }

    @Override
    public ResultInfo query(String loginId, Map<String, Object> map) {
        try{
            JSONObject jsonObject = getData(map,loginId);
            if (StringUtils.isEmpty(loginId)){
                return new ResultInfo(500,"用户信息丢失！",null);
            }else{
                String curpage = "",pagesize="",cxmc="",state="",dlmc="";
                QueryWrapper<TCzy> queryWrapper = new QueryWrapper<>();
                if (jsonObject.containsKey("curpage")) {
                    curpage = jsonObject.getString("curpage");
                }
                if (jsonObject.containsKey("pagesize")) {
                    pagesize = jsonObject.getString("pagesize");
                }
                if (jsonObject.containsKey("cxmc")) {
                    cxmc = jsonObject.getString("cxmc");
                }
                if (jsonObject.containsKey("state")) {
                    state = jsonObject.getString("state");
                }
                if (jsonObject.containsKey("dlmc")) {
                    dlmc = jsonObject.getString("dlmc");
                }

                if (StringUtils.isEmpty(curpage)) curpage = "1";
                if (StringUtils.isEmpty(pagesize)) pagesize = "10";

                Page<TCzy> page = new Page<>( Integer.parseInt(curpage),  Integer.parseInt(pagesize));

                ListInfo<TCzy> tCzyListInfo = new ListInfo<>();
                if (!StringUtils.isEmpty(dlmc))
                {
                    queryWrapper.like("dlmc",dlmc);
                }
                if (!StringUtils.isEmpty(cxmc))
                {
                    queryWrapper.like("name",cxmc);
                }
                if (!StringUtils.isEmpty(state))
                {
                    queryWrapper.eq("state",state);
                }
                queryWrapper.ne("dlmc","admin");

                queryWrapper.orderByDesc("id");
                IPage<TCzy> tCzyLPage = getBaseMapper().getTCzyLPage(page,queryWrapper);

                PageInfo pageInfo = new PageInfo();
                pageInfo.setTotal(tCzyLPage.getTotal());
                pageInfo.setCurPage(tCzyLPage.getCurrent());
                pageInfo.setPageSize(tCzyLPage.getSize());
                pageInfo.setPageTotal(tCzyLPage.getPages());

                tCzyListInfo.setPageInfo(pageInfo);
                tCzyListInfo.setListInfo(tCzyLPage.getRecords());
                tCzyListInfo.setUserId(loginId);

                //查询条件的值
                Map<String,Object> cxtjMap = new HashMap<>();
                cxtjMap.put("cxmc",cxmc);
                cxtjMap.put("dlmc",dlmc);
                cxtjMap.put("state",state);

                //返回前端的内容
                Map<String,Object> rtnMap = new HashMap<>();
                rtnMap.put("cxjg",tCzyListInfo);
                rtnMap.put("cxtj",cxtjMap);

                ResultInfo resultInfo = new ResultInfo(0, "成功返回！",rtnMap);
                return backRtn(resultInfo,loginId);
            }
        }catch (Exception e){
            e.printStackTrace();
            ResultInfo resultInfo = new ResultInfo(500, "成功返回！",null);
            return backRtn(resultInfo,loginId);
        }

    }

    @Transactional
    public ResultInfo czmm(String loginId, Map<String, Object> map) {
        JSONObject jsonObject = getData(map,loginId);
        if (StringUtils.isEmpty(loginId)){
            throw new RuntimeException("用户信息丢失!");
        }else{
            TCzy tCzy = getBaseMapper().getCzyById(loginId);
            String id = "";
            if (jsonObject.containsKey("id")) {
                id = jsonObject.getString("id");
            }

            if (StringUtils.isEmpty(id))
            {
                return new ResultInfo(500,"没有需要修改密码的用户信息！",null);
            }

            String pwd = ToolBean.getMD5Str("111111");
            int a = getBaseMapper().updateUserPwd(pwd,id);

            if (a>0)
            {
                return new ResultInfo(9,"密码修改成功！",null);
            }else{
                return new ResultInfo(500,"修改密码的用户信息不存在！",null);
            }

        }
    }

    @Override
    public ResultInfo info(String loginId, Map<String, Object> map) {
        JSONObject jsonObject = getData(map,loginId);
        if (StringUtils.isEmpty(loginId)){
            return new ResultInfo(500,"用户信息丢失！",null);
        }else{
            TCzy tCzy = new TCzy();
            tCzy = getBaseMapper().selectById(loginId);

            Map<String,Object> infoMap = new HashMap<>();

            String id="";
            if (jsonObject.containsKey("id")) {
                id = jsonObject.getString("id");
            }
            String lx="";
            if (jsonObject.containsKey("lx")) {
                lx = jsonObject.getString("lx");
            }

            //除了admin，只能选自己建立的角色信息
            List<TRole> tRoleList = new ArrayList<>();
            if("1".equals(loginId)){
                tRoleList = tRoleDao.selectList(new QueryWrapper<TRole>().eq("state","1"));
            }else{
                Long role_id = tCzy.getRoleId();
                tRoleList = tRoleDao.selectList(new QueryWrapper<TRole>().eq("state","1").and(qr->qr.eq("t_czy_id",loginId).or().eq("id",role_id)));
            }

            //除了admin，只能选自己所在机构或者下级机构
            List<TXzjg> tXzjgList = new ArrayList<>();
            if("1".equals(loginId)){
                tXzjgList = tXzjgDao.selectList(new QueryWrapper<TXzjg>().eq("state","1"));
            }else{
                tXzjgList = tXzjgDao.getXzjgXj(tCzy.getXzjgId());
            }

            if ("1".equals(lx)){
                TCzy tCzy1 = new TCzy();
                tCzy1 = getBaseMapper().selectById(id);
                infoMap.put("tCzy",tCzy1);
            }

            infoMap.put("tRoleList",tRoleList);
            infoMap.put("tXzjgList",tXzjgList);
            ResultInfo resultInfo = new ResultInfo(0, "成功返回！",infoMap);
            return backRtn(resultInfo,loginId);
        }
    }

    @Override
    public ResultInfo save(String loginId, Map<String, Object> map) {
        JSONObject jsonObject = getData(map,loginId);
        if (StringUtils.isEmpty(loginId)){
            return new ResultInfo(500,"用户信息丢失！",null);
        }else{
            String lx="",id="",nonce_ms="",nonce_zhi="",yhmc="",dlmc="",xzjg_id="",role_id="";
            String pwd = ToolBean.getMD5Str("111111");
            if (jsonObject.containsKey("lx")) {
                lx = jsonObject.getString("lx");
            }
            if (jsonObject.containsKey("id")) {
                id = jsonObject.getString("id");
            }
            if (jsonObject.containsKey("yhmc")) {
                yhmc = jsonObject.getString("yhmc");
            }
            if (jsonObject.containsKey("dlmc")) {
                dlmc = jsonObject.getString("dlmc");
            }
            if (jsonObject.containsKey("xzjg_id")) {
                xzjg_id = jsonObject.getString("xzjg_id");
            }
            if (jsonObject.containsKey("role_id")) {
                role_id = jsonObject.getString("role_id");
            }
            if (jsonObject.containsKey("nonce_ms")) {
                nonce_ms = jsonObject.getString("nonce_ms");
            }
            if (jsonObject.containsKey("nonce_zhi")) {
                nonce_zhi = jsonObject.getString("nonce_zhi");
            }
            //参数校验
            if (StringUtils.isEmpty(dlmc) || StringUtils.isEmpty(yhmc) || StringUtils.isEmpty(xzjg_id) || StringUtils.isEmpty(role_id)){
                return new ResultInfo(500,"关键参数丢失！",null);
            }
            long sl = 0L;
            if ("0".equals(lx)){
                sl= getBaseMapper().selectCount(new QueryWrapper<TCzy>().eq("dlmc",dlmc));
            }else{
                sl = getBaseMapper().selectCount(new QueryWrapper<TCzy>().eq("dlmc",dlmc).ne("id",id));
            }
            if (sl > 0) {
                return new ResultInfo(500,"登录名称重复！",null);
            }
            //校验nonce
            ResultInfo ResultInfoCheckNonce = new ResultInfo();
            ResultInfoCheckNonce = tApiNonceService.checkNonce(nonce_ms,loginId,nonce_zhi,"用户信息增改操作！");

            if (ResultInfoCheckNonce.getCode()!=200)
            {
                return ResultInfoCheckNonce;
            }

            TCzy tCzy = getBaseMapper().getCzyById(loginId);

            TCzy tCzyNew = new TCzy();
            if ("1".equals(lx)){
                tCzyNew = getBaseMapper().selectById(id);
            }
            tCzyNew.setDlmc(dlmc);
            tCzyNew.setName(yhmc);
            tCzyNew.setZjm(ToolBean.getPy(yhmc));
            if (!StringUtils.isEmpty(role_id)) {
                tCzyNew.setRoleId(Long.parseLong(role_id));
            }
            if (!StringUtils.isEmpty(xzjg_id)) {
                tCzyNew.setXzjgId(Long.parseLong(xzjg_id));
            }
            tCzyNew.setPwd(pwd);
            tCzyNew.setTCzyId(tCzy.getId());
            ResultInfo resultInfo;
            if ("1".equals(lx)){
                if (!String.valueOf(tCzyNew.getTCzyId()).equals(loginId) && !"1".equals(loginId)){
                    return new ResultInfo(500,"非自己维护的信息不得修改！",null);
                }
                getBaseMapper().updateById(tCzyNew);
                resultInfo = new ResultInfo(2, "修改成功！",null);
            }else{
                getBaseMapper().insert(tCzyNew);
                resultInfo = new ResultInfo(1, "新增成功！",null);
            }
            return backRtn(resultInfo,loginId);
        }
    }

    @Override
    @Transactional
    public ResultInfo del(String loginId, Map<String, Object> map) {
        JSONObject jsonObject = getData(map,loginId);
        if (StringUtils.isEmpty(loginId)){
            return new ResultInfo(500,"用户信息丢失！",null);
        }else{
            String ids = "";
            if (jsonObject.containsKey("ids")) {
                ids = jsonObject.getString("ids");
            }
            String [] code = ids.split(",");
            int i=0;
            String str="";

            TCzy tCzy = getBaseMapper().getCzyById(loginId);
            TCzy tCzyDel = new TCzy();

            for(i=0;i<code.length;i++)
            {
                if (code[i].equals("")) {
                    continue;
                }
                String id = code[i].replaceAll("\\D","").trim();
                tCzyDel = getBaseMapper().getCzyById(id);
                if (!tCzy.getId().equals(tCzyDel.getTCzyId())){
                    return new ResultInfo(500,"不能删除非自己维护的用户信息！",null);
                }
                getBaseMapper().delCzy("0",id);
            }
            return new ResultInfo(3,"删除成功！",null);
        }
    }
}
